package com.tulele.vtool.handler;

import com.google.common.collect.Maps;
import com.tulele.vtool.model.SysUser;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.model.reqEntity.BackendInterfaceLoginBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.SysUserService;
import com.tulele.vtool.utils.RedisCacheUtil;
import com.tulele.vtool.utils.SysConstant;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("backendInterface")
public class BackendInterface {
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    /**
     * 后台扫码绑定
     *
     * @param backendInterfaceLoginBean 实例对象
     * @return 实例对象
     */
    @PostMapping(value = "/binding", produces = "application/json;charset=UTF-8")
    public RespData binding(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @RequestBody BackendInterfaceLoginBean backendInterfaceLoginBean) {
        RespData respData = new RespData();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(springProfilesActive) || backendInterfaceLoginBean == null || StringUtils.isBlank(backendInterfaceLoginBean.getUniqueness()) || StringUtils.isBlank(backendInterfaceLoginBean.getSysUser()) || StringUtils.isBlank(backendInterfaceLoginBean.getOrigin())) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        String origin = backendInterfaceLoginBean.getOrigin();
        String uuid = backendInterfaceLoginBean.getUniqueness();
        String verifyKey = SysConstant.BINDING_QR_CODE_KEY + uuid;

        Object qrCodeStatus = Optional.ofNullable(redisCacheUtil.getCacheObjectMaster(verifyKey)).orElse(null);

        if (qrCodeStatus != null) {
            String lastQrCodeStatus = qrCodeStatus.toString();

            if (lastQrCodeStatus.contains(SysConstant.QR_CODE_STATUS_HAS)) {
                Integer userIdInt = Integer.valueOf(userId);
                UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

                String openId = userInfo.getOpenId();

                if (StringUtils.isNotBlank(openId)) {
                    if(origin.equals("8000")) {
                        SysUser sysUser = sysUserService.queryByOpenId_zktdb(openId);

                        if (sysUser == null) {

                            Long sysUserId = Long.parseLong(backendInterfaceLoginBean.getSysUser());
                            SysUser sysUserInfo = sysUserService.queryById_zktdb(sysUserId);

                            if (sysUserInfo == null) {
                                redisCacheUtil.removeSingleCacheMaster(verifyKey);
                                respData.setCode(ReturnCode.CLIENT_ERROR);
                                respData.setMsg("账号不存在");
                                return respData;
                            }

                            if (StringUtils.isBlank(sysUserInfo.getOpenId())) {
                                sysUserInfo.setOpenId(openId);
                                sysUserService.updateOpenId_zktdb(sysUserInfo);

                                redisCacheUtil.setCacheObjectMaster(verifyKey, SysConstant.QR_CODE_STATUS_OK_ORIGIN_ONE + sysUserInfo.getUserId(), SysConstant.QR_CODE_EXPIRATION);
                                respData.setCode(ReturnCode.NORMAL_SUCC);
                                respData.setMsg("操作成功");
                                return respData;
                            }

                            redisCacheUtil.removeSingleCacheMaster(verifyKey);
                            respData.setCode(ReturnCode.CLIENT_ERROR);
                            respData.setMsg("账号已绑定其他微信");
                            return respData;

                        }

                        redisCacheUtil.removeSingleCacheMaster(verifyKey);
                        respData.setCode(ReturnCode.CLIENT_ERROR);
                        respData.setMsg("微信已绑定账号");
                        return respData;
                    }

                    if(origin.equals("6001")) {
                        SysUser sysUser = sysUserService.queryByOpenId_gzhdbjssq(openId);

                        if (sysUser == null) {

                            Long sysUserId = Long.parseLong(backendInterfaceLoginBean.getSysUser());
                            SysUser sysUserInfo = sysUserService.queryById_gzhdbjssq(sysUserId);

                            if (sysUserInfo == null) {
                                redisCacheUtil.removeSingleCacheMaster(verifyKey);
                                respData.setCode(ReturnCode.CLIENT_ERROR);
                                respData.setMsg("账号不存在");
                                return respData;
                            }

                            if (StringUtils.isBlank(sysUserInfo.getOpenId())) {
                                sysUserInfo.setOpenId(openId);
                                sysUserService.updateOpenId_gzhdbjssq(sysUserInfo);

                                redisCacheUtil.setCacheObjectMaster(verifyKey, SysConstant.QR_CODE_STATUS_OK_ORIGIN_TWO + sysUserInfo.getUserId(), SysConstant.QR_CODE_EXPIRATION);
                                respData.setCode(ReturnCode.NORMAL_SUCC);
                                respData.setMsg("操作成功");
                                return respData;
                            }

                            redisCacheUtil.removeSingleCacheMaster(verifyKey);
                            respData.setCode(ReturnCode.CLIENT_ERROR);
                            respData.setMsg("账号已绑定其他微信");
                            return respData;

                        }

                        redisCacheUtil.removeSingleCacheMaster(verifyKey);
                        respData.setCode(ReturnCode.CLIENT_ERROR);
                        respData.setMsg("微信已绑定账号");
                        return respData;
                    }
                }

            }

            if (lastQrCodeStatus.contains(SysConstant.QR_CODE_STATUS_OK)) {
                respData.setCode(ReturnCode.CLIENT_ERROR);
                respData.setMsg("二维码已失效");
                return respData;
            }

        }

        respData.setCode(ReturnCode.CLIENT_ERROR);
        respData.setMsg("操作失败");
        return respData;
    }

    /**
     * 后台扫码登录
     *
     * @param backendInterfaceLoginBean 实例对象
     * @return 实例对象
     */
    @PostMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public RespData login(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @RequestBody BackendInterfaceLoginBean backendInterfaceLoginBean) {
        RespData respData = new RespData();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(springProfilesActive) || backendInterfaceLoginBean == null || StringUtils.isBlank(backendInterfaceLoginBean.getUniqueness()) || StringUtils.isBlank(backendInterfaceLoginBean.getOrigin())) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        String origin = backendInterfaceLoginBean.getOrigin();
        String uuid = backendInterfaceLoginBean.getUniqueness();
        String verifyKey = SysConstant.LOGIN_QR_CODE_KEY + uuid;

        Object qrCodeStatus = Optional.ofNullable(redisCacheUtil.getCacheObjectMaster(verifyKey)).orElse(null);

        if (qrCodeStatus != null) {
            String lastQrCodeStatus = qrCodeStatus.toString();

            if (lastQrCodeStatus.contains(SysConstant.QR_CODE_STATUS_HAS)) {
                Integer userIdInt = Integer.valueOf(userId);
                UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

                String openId = userInfo.getOpenId();

                if (StringUtils.isNotBlank(openId)) {
                    if(origin.equals("8000")) {
                        SysUser sysUser = sysUserService.queryByOpenId_zktdb(openId);

                        if (sysUser != null) {
                            redisCacheUtil.setCacheObjectMaster(verifyKey, SysConstant.QR_CODE_STATUS_OK_ORIGIN_ONE + sysUser.getUserId(), SysConstant.QR_CODE_EXPIRATION);

                            respData.setCode(ReturnCode.NORMAL_SUCC);
                            respData.setMsg("操作成功");
                            return respData;
                        }
                    }

                    if(origin.equals("6001")) {
                        SysUser sysUser = sysUserService.queryByOpenId_gzhdbjssq(openId);

                        if (sysUser != null) {
                            redisCacheUtil.setCacheObjectMaster(verifyKey, SysConstant.QR_CODE_STATUS_OK_ORIGIN_TWO + sysUser.getUserId(), SysConstant.QR_CODE_EXPIRATION);

                            respData.setCode(ReturnCode.NORMAL_SUCC);
                            respData.setMsg("操作成功");
                            return respData;
                        }
                    }
                }
            }

            if (lastQrCodeStatus.contains(SysConstant.QR_CODE_STATUS_OK)) {
                respData.setCode(ReturnCode.CLIENT_ERROR);
                respData.setMsg("二维码已失效");
                return respData;
            }
        }

        respData.setCode(ReturnCode.CLIENT_ERROR);
        respData.setMsg("操作失败");
        return respData;
    }

    /**
     * 后台扫码登录二维码状态
     *
     * @param backendInterfaceLoginBean 实例对象
     * @return 实例对象
     */
    @PostMapping(value = "/qrCodeStatus", produces = "application/json;charset=UTF-8")
    public RespData qrCodeStatus(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @RequestBody BackendInterfaceLoginBean backendInterfaceLoginBean) {
        RespData respData = new RespData();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(springProfilesActive) || backendInterfaceLoginBean == null || StringUtils.isBlank(backendInterfaceLoginBean.getUniqueness()) || StringUtils.isBlank(backendInterfaceLoginBean.getQrCodeType())) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        String qrCodeType = backendInterfaceLoginBean.getQrCodeType();
        String uuid = backendInterfaceLoginBean.getUniqueness();
        String verifyKey = SysConstant.LOGIN_QR_CODE_KEY + uuid;

        if (qrCodeType.equals("login")) {
            verifyKey = SysConstant.LOGIN_QR_CODE_KEY + uuid;
        } else if (qrCodeType.equals("binding")) {
            verifyKey = SysConstant.BINDING_QR_CODE_KEY + uuid;
        }


        Object qrCodeStatus = Optional.ofNullable(redisCacheUtil.getCacheObjectMaster(verifyKey)).orElse(null);

        if (qrCodeStatus != null) {
            String lastQrCodeStatus = qrCodeStatus.toString();

            if (lastQrCodeStatus.contains(SysConstant.QR_CODE_STATUS_NOT)) {

                redisCacheUtil.setCacheObjectMaster(verifyKey, SysConstant.QR_CODE_STATUS_HAS, SysConstant.QR_CODE_EXPIRATION);
                respData.setCode(ReturnCode.NORMAL_SUCC);
                respData.setMsg("操作成功");
                return respData;
            }

            if (lastQrCodeStatus.contains(SysConstant.QR_CODE_STATUS_HAS)) {
                respData.setCode(ReturnCode.CLIENT_ERROR);
                respData.setMsg("二维码已失效");
                return respData;
            }
        }

        respData.setCode(ReturnCode.CLIENT_ERROR);
        respData.setMsg("操作失败");
        return respData;
    }

    /**
     * 后台扫码生成UUID
     *
     * @param backendInterfaceLoginBean 实例对象
     * @return 实例对象
     */
    @PostMapping(value = "/loginUUID", produces = "application/json;charset=UTF-8")
    public RespData loginUUID(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @RequestBody BackendInterfaceLoginBean backendInterfaceLoginBean) {
        RespData respData = new RespData();

        String uuid = backendInterfaceLoginBean.getUniqueness();
        uuid = "1781143d2db04ed681ee17bfd3ba1cb5";
        String qrCodeType = backendInterfaceLoginBean.getQrCodeType();
        String verifyKey = SysConstant.LOGIN_QR_CODE_KEY + uuid;

        if (qrCodeType.equals("login")) {
            verifyKey = SysConstant.LOGIN_QR_CODE_KEY + uuid;
        } else if (qrCodeType.equals("binding")) {
            verifyKey = SysConstant.BINDING_QR_CODE_KEY + uuid;
        }

        redisCacheUtil.setCacheObjectMaster(verifyKey, SysConstant.QR_CODE_STATUS_NOT, SysConstant.QR_CODE_EXPIRATION);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);

        resultMap.put("uuid", uuid);
        respData.setData(resultMap);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("生成UUID成功");
        return respData;
    }
}
